from flask import Flask, request, jsonify
from app.config import Config
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object(Config)
engine = create_engine(Config.SQLALCHEMY_DATABASE_URI, pool_recycle=3600)
DBSession = sessionmaker(bind=engine)

dBSession = DBSession()
from . import models, routes, services, templates

routes.init_app(app)
templates.templates_init(app)
models.db = SQLAlchemy(app)


@app.teardown_appcontext
def shutdown_session(exception=None):
    dBSession.close()


@app.errorhandler(404)
def notFound(err):
    err_split = str(err).split(':')
    err_split = [x.strip() for x in err_split]
    response = f'<h1>{err_split[0]}</h1>\n<h2>{err_split[1]}</h2>'
    return response, 404

# @app.errorhandler(500)
# def serverError(err):
#     if request.method == 'POST':
#         err_split = str(err).split(':')
#         err_split = [x.strip() for x in err_split]
#         response = {
#             'status': 500,
#             'message': err_split[2]
#         }
#         return jsonify(response)
#     elif request.method == 'GET':
#         err_split = str(err).split(':')
#         err_split = [x.strip() for x in err_split]
#         response = f'<h1>{err_split[0]}</h1>\n<h2>{err_split[1]}</h2>'
#         return response, 500
#     else:
#         return err, 500
